package com.diyunapp.xilinapp.details;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.PopListAdapter;
import com.diyunapp.xilinapp.bean.FaPiaoBean;
import com.diyunapp.xilinapp.bean.PopList;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.diyunapp.xilinapp.utils.FormatConfirm;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by NIDAYE on 2016/7/1.
 */
public class FaPiaoActivity extends StatusBarActivity implements View.OnClickListener {

    @Bind(R.id.order_confirm_goback_ib)
    ImageButton orderConfirmGobackIb;
    @Bind(R.id.fapiao_select_rg)
    RadioGroup fapiaoSelectRg;
    @Bind(R.id.fapiao_set_tv)
    TextView fapiaoSetTv;
    @Bind(R.id.fapiao_delete_tv)
    TextView fapiaoDeleteTv;
    @Bind(R.id.fapiao_new_tv)
    TextView fapiaoNewTv;
    @Bind(R.id.fapiao_head_tv)
    TextView fapiaoHeadTv;
    @Bind(R.id.fapiao_head_ll)
    LinearLayout fapiaoHeadLl;
    @Bind(R.id.dropdown_fapiaohead_view)
    View dropdownFapiaoheadView;
    @Bind(R.id.fapaio_company_et)
    EditText fapaioCompanyEt;
    @Bind(R.id.fapaio_company_ll)
    LinearLayout fapaioCompanyLl;
    @Bind(R.id.fapiao_content_tv)
    TextView fapiaoContentTv;
    @Bind(R.id.fapiao_content_ll)
    LinearLayout fapiaoContentLl;
    @Bind(R.id.dropdown_fapiaocontent_view)
    View dropdownFapiaocontentView;
    @Bind(R.id.addfapiao_ll)
    LinearLayout addfapiaoLl;
    @Bind(R.id.fapiao_sv)
    ScrollView fapiaoSv;

    private String invId = "";
    private List<FaPiaoBean> myFapiaoList = new ArrayList<>();
    private String loginKey = "d27d6a1b8abec70888744a6b39d9c635";
    private int selectInvID = -1;   //标识选中发票在myFapiaoList中的位置
    private int selectRadBID = -1;  //标识选中发票在RadioGroup中的位置

    private List<PopList> headList = new ArrayList<>();
    private List<PopList> typeList = new ArrayList<>();

    private PopListAdapter headAdapter;
    private PopListAdapter typeAdapter;

    private PopupWindow headPop;
    private PopupWindow typePop;

    private int headSelected = 0;
    private int typeSelected = 0;

    private boolean isNewAdd = false;

    private View headView;

    private HashMap<Integer, Integer> fapiaoIDHash = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fapiao_layout);
        ButterKnife.bind(this);
        loginKey = MainActivity.myLogin.getLoginkey();
        invId = getIntent().getStringExtra("InvId");
        initViews();
        if(!invId.equals("nofapiao"))
        {
            getFapiaoInfo();
        }

        getContentInfo();
        fapiaoSv.scrollTo(0,0);
    }

    private void initViews() {

        headView = findViewById(R.id.fapiao_set_menubar_inc);
        super.MenuWidget(headView);

        orderConfirmGobackIb.setOnClickListener(this);
        fapiaoSetTv.setOnClickListener(this);
        fapiaoDeleteTv.setOnClickListener(this);
        fapiaoNewTv.setOnClickListener(this);
        fapiaoHeadLl.setOnClickListener(this);
        fapiaoContentLl.setOnClickListener(this);

        headList.add(new PopList(0, "个人"));
        headList.add(new PopList(1, "单位"));

        View headPopRoot = LayoutInflater.from(this).inflate(R.layout.poplistlayout, null);
        ListView headLV = (ListView) headPopRoot.findViewById(R.id.pop_list_view);
        headAdapter = new PopListAdapter(this, headList);
        headLV.setAdapter(headAdapter);
        headLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                headSelected = position;
                headPop.dismiss();
                fapiaoHeadTv.setText(headList.get(position).getPop_info());
                if (headList.get(position).getPop_info().equals("单位")) {
                    fapaioCompanyLl.setVisibility(View.VISIBLE);
                } else {
                    fapaioCompanyLl.setVisibility(View.GONE);
                }
            }
        });

        headPop = new PopupWindow(headPopRoot, 480, LinearLayout.LayoutParams.WRAP_CONTENT);
        // 点击外部可关闭窗口
        headPop.setBackgroundDrawable(FormatConfirm.getDrawable(FaPiaoActivity.this));
        headPop.setOutsideTouchable(true);
        headPop.setFocusable(true);

        View typePopRoot = LayoutInflater.from(this).inflate(R.layout.poplistlayout, null);
        ListView typeLV = (ListView) typePopRoot.findViewById(R.id.pop_list_view);
        typeAdapter = new PopListAdapter(this, typeList);
        typeLV.setAdapter(typeAdapter);
        typeLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                typeSelected = position;
                typePop.dismiss();
                fapiaoContentTv.setText(typeList.get(position).getPop_info());

            }
        });

        typePop = new PopupWindow(typePopRoot, 480, LinearLayout.LayoutParams.WRAP_CONTENT);
        // 点击外部可关闭窗口
        typePop.setBackgroundDrawable(FormatConfirm.getDrawable(FaPiaoActivity.this));
        typePop.setOutsideTouchable(true);
        typePop.setFocusable(true);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_confirm_goback_ib:
                setResult(0);
                finish();
                break;
            case R.id.fapiao_set_tv:
                if(selectInvID<0)
                {
                    Toast.makeText(getApplicationContext(),"没有可使用的发票信息！",Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent fapiaoInt = new Intent();
                    Bundle seletedFapiaoBd = new Bundle();
                    seletedFapiaoBd.putSerializable("InvFapiao", myFapiaoList.get(selectInvID));
                    fapiaoInt.putExtra("FapiaoBundle", seletedFapiaoBd);
                    setResult(1, fapiaoInt);
                    finish();
                }
                break;
            case R.id.fapiao_delete_tv:
                if(selectInvID<0)
                {
                    Toast.makeText(getApplicationContext(),"没有可删除的发票信息！",Toast.LENGTH_SHORT).show();
                }
                else{
                    deleteFapiao();
                }

                break;
            case R.id.fapiao_new_tv:
                if (isNewAdd) {
                    addFapiao();
                } else {
                    addfapiaoLl.setVisibility(View.VISIBLE);
                    isNewAdd = true;
                    fapiaoNewTv.setText("保存");
                }
                break;
            case R.id.fapiao_head_ll:
                headPop.showAsDropDown(dropdownFapiaoheadView);
                break;
            case R.id.fapiao_content_ll:
                typePop.showAsDropDown(dropdownFapiaocontentView);
                break;
            default:
                break;
        }
    }

    private void displayFapiao() {

        fapiaoSelectRg.removeAllViews();
        fapiaoIDHash.clear();

        if( myFapiaoList.size()<1)
        {
            return;
        }

        for (int i = 0,j=0; i < myFapiaoList.size(); i++,j+=4) {
            RadioButton tempButton = new RadioButton(this);
            tempButton.setButtonDrawable(R.drawable.paytype_radiobuttion_selector);           // 设置按钮的样式
            tempButton.setPadding(20, 0, 0, 0);// 设置文字距离按钮四周的距离

            tempButton.setText(myFapiaoList.get(i).getInv_describe());
            tempButton.setTextColor(getResources().getColor(R.color.grey_good_evaluate));
            tempButton.setTextSize(13);
            fapiaoSelectRg.addView(tempButton);
            fapiaoIDHash.put(tempButton.getId(), j);
            if(myFapiaoList.get(i).getInv_id().equals(invId))
            {
                selectRadBID = j;
            }

            //加上占空的view
            View blankViewUp = new View(this);
            blankViewUp.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,15));
            fapiaoSelectRg.addView(blankViewUp);
            fapiaoIDHash.put(blankViewUp.getId(), j + 1);

            //加上占空的view
            View lineView = new View(this);
            lineView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,1));
            lineView.setBackgroundColor(getResources().getColor(R.color.grey_seperator));
            fapiaoSelectRg.addView(lineView);
            fapiaoIDHash.put(blankViewUp.getId(), j + 2);

            //加上占空的view
            View blankViewDown = new View(this);
            blankViewDown.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,15));
            fapiaoSelectRg.addView(blankViewDown);
            fapiaoIDHash.put(blankViewDown.getId(), j + 3);

        }

        fapiaoSelectRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                selectRadBID = fapiaoIDHash.get(checkedId);
                selectInvID = selectRadBID/4;
            }
        });

        ((RadioButton) fapiaoSelectRg.getChildAt(selectRadBID)).setChecked(true);
    }

    //读取用户的发票列表
    private void getFapiaoInfo() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_invoice&op=invoice_list";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "certify_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "读取发票失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            } else {
                                myFapiaoList.clear();
                                JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                                JSONArray jsArrayInv = jsObjectDatas.getJSONArray("invoice_list");
                                for (int i = 0; i < jsArrayInv.length(); i++) {
                                    JSONObject jsObjectInv = jsArrayInv.getJSONObject(i);
                                    String inv_id = jsObjectInv.getString("inv_id");
                                    String inv_title = jsObjectInv.getString("inv_title");
                                    String inv_content = jsObjectInv.getString("inv_content");
                                    String des = inv_title + "    " + inv_content;

                                    myFapiaoList.add(new FaPiaoBean(inv_id, inv_title, inv_content, des, inv_title));

                                    if (invId.equals(inv_id)) {
                                        selectInvID = i;
                                    }
                                }

                                if(myFapiaoList.size()<1)
                                {
                                    selectInvID = -1;
                                    selectRadBID = -1;
                                }
                                displayFapiao();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplicationContext(), "读取发票失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    //读取发票购买内容的设置列表
    private void getContentInfo() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_invoice&op=invoice_content_list";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "读取发票内容失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            } else {
                                JSONObject jsObjectDatas = jsObjectCode.getJSONObject("datas");
                                String contentStr = jsObjectDatas.getString("invoice_content_list");

                                if (contentStr.length() > 20) {
                                    parseContent(contentStr);
                                } else {
                                    Toast.makeText(getApplicationContext(), "发票可选内容为空，请联系客服处理！", Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "读取发票内容失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void addFapiao() {
        final String headstr = headList.get(headSelected).getPop_info();
        final String typeStr = typeList.get(typeSelected).getPop_info();
        final String companyInfo = fapaioCompanyEt.getText().toString();

        String url = "http://www.xilingou.com/mobile/index.php?act=member_invoice&op=invoice_add";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("inv_title_select", headstr);
        if (headSelected > 0) {
            if (companyInfo.length() <= 0) {
                Toast.makeText(getApplicationContext(), "请填写单位名称！", Toast.LENGTH_LONG).show();
                return;
            } else {
                params.addBodyParameter("inv_title", companyInfo);
            }
        } else {
            params.addBodyParameter("inv_title", headstr);
        }

        params.addBodyParameter("inv_content", typeStr);

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "发票添加失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            } else {
                                JSONObject jsobjectDatas = jsObjectCode.getJSONObject("datas");
                                invId = jsobjectDatas.getString("inv_id");
                                Toast.makeText(getApplicationContext(), "添加成功！", Toast.LENGTH_LONG).show();
                                addfapiaoLl.setVisibility(View.GONE);
                                isNewAdd = false;
                                fapiaoNewTv.setText("新增");
                                getFapiaoInfo();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "发票添加失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void deleteFapiao() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_invoice&op=invoice_del";
        RequestParams params = new RequestParams();
        params.addBodyParameter("key", loginKey);
        params.addBodyParameter("inv_id", myFapiaoList.get(selectInvID).getInv_id());

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(200);
        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "content_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                Toast.makeText(getApplicationContext(), "发票删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                            } else {
                                String datas = jsObjectCode.getString("datas");
                                if (datas.equals("1")) {
                                    Toast.makeText(getApplicationContext(), "删除成功！", Toast.LENGTH_LONG).show();
                                    selectInvID = 0;
                                    selectRadBID = 0;
                                    getFapiaoInfo();
                                } else {
                                    JSONObject jsobjectDatas = new JSONObject(datas);
                                    String errors = jsobjectDatas.getString("error");
                                    Toast.makeText(getApplicationContext(), errors, Toast.LENGTH_LONG).show();
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure msg=" + msg);
                        Toast.makeText(getApplicationContext(), "发票删除失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void parseContent(String contentStr) {

        Log.i("zhangxiaoxidebug", "contentStr=" + contentStr);
        String tempStr1 = contentStr.replace("[", "");
        String tempStr2 = tempStr1.replace("]", "");

        String srcStr = tempStr2;
        for (int i = 0; ; i++) {
            Log.i("zhangxiaoxidebug", "srcStr=" + srcStr);
            int index = srcStr.indexOf(",");
            if (index > 0) {
                String valueMiddle = srcStr.substring(1, index - 1);
                Log.i("zhangxiaoxidebug", "valueMiddle=" + valueMiddle);
                typeList.add(new PopList(i, valueMiddle));
                String tempSrc = srcStr.substring(index + 1, srcStr.length());
                srcStr = tempSrc;
            } else {
                String valueLast = srcStr.substring(1, srcStr.length() - 1);
                Log.i("zhangxiaoxidebug", "valueLast=" + valueLast);
                typeList.add(new PopList(i, valueLast));
                break;
            }
        }
        typeAdapter.notifyDataSetChanged();
    }


}
